<?php
namespace app\home\controller;

use app\common\logic\User AS UserLogic;
use app\common\component\user\UserModel;
use app\common\component\user\UserService;
use app\common\component\user\UserValidate;
use app\common\component\user_vip\UserVipService;

class Auth extends ControllerBase {
	public function login() {
		$post = $this -> request -> post();

		$resultUserValidate = (new UserValidate) -> login($post);
		if($resultUserValidate['code'] !== 0) {
			return json($resultUserValidate);
		}

		$loginUser = (new UserService) -> login($post);
		return json($loginUser);
	}

	public function forgetPassword() {
		$post = $this -> request -> post();

		$getUser = UserModel::get(['username' => $post['username']]);

		if(!$getUser) {
			return [
				'code' => -1,
				'message' => '账号不存在！'
			];
		}

		$code = \think\Cache::get('sendCode_'.$getUser -> user_id);

		if(!$code) {
			return [
				'code' => -1,
				'message' => '验证码错误！'
			];
		}
		
		if($code != $post['code']) {
			return [
				'code' => -1,
				'message' => '验证码错误！'
			];
		}
		
		if($post['password'] != $post['comfirm_password']) {
			return [
				'code' => -1,
				'message' => '输入的密码不一致！'
			];
		}

		$getUser -> password = getPasswordHash($post['password']);
		
		if($getUser -> save()) {
			return [
				'code' => 0,
				'message' => '修改成功！'
			];
		}

		return [
			'code' => -1,
			'message' => '修改失败！'
		];
	}
	
	public function sendCode() {
		$result = ['code' => -1, 'message' => '非法操作!'];
		$post = $this -> request -> post();
		$getUser = UserModel::get(['username' => $post['username']]);

		if(!$getUser) {
			$result['code'] = -1;
			$result['message'] = '账号不存在';
		} else {
			$code = crypto_rand(22222, 99999);
			\think\Cache::set('sendCode_'.$getUser -> user_id, $code, 300);

			$result['code'] = 0;
			$result['message'] = winicSMS($getUser -> phone, ['code' => $code], 90);
		}

		return json($result);
	}

	public function logout() {
		(new UserService) -> clearLoginSession();
		$this -> redirect('home/Index/index');
	}

	public function register() {
		$resultUser = (new UserLogic) -> register2($this -> request -> post());
		return json($resultUser);
		/*
		if($resultUser['code'] === 0) {
			echo '<meta charset="utf-8"><script>alert("' . $resultUser['message'] . '!");window.location.href="/";</script>';exit;
		}
		*/
	}
}